package com.daxidi.cn.controller;


import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daxidi.cn.annotation.LogAnnotation;
import com.daxidi.cn.entity.Clerk;
import com.daxidi.cn.entity.User;
import com.daxidi.cn.enums.LogTypeEnum;
import com.daxidi.cn.mapper.ClerkMapper;
import com.daxidi.cn.mapper.UserMapper;
import com.daxidi.cn.params.AddClerkParam;
import com.daxidi.cn.params.UpdateClerkParam;
import com.daxidi.cn.params.UpdateClerkPassword;
import com.daxidi.cn.service.IClerkService;
import com.daxidi.cn.utils.ReturnResult;
import com.daxidi.cn.utils.ReturnResultUtils;
import com.daxidi.cn.utils.UuidUtils;
import com.daxidi.cn.vo.ClerkVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商家店员信息表 前端控制器
 * </p>
 *
 * @author wsh
 * @since 2020-11-09
 */
@Log4j
@Api(tags = "商家店员信息模块接口")
@RestController
@RequestMapping(value = "/api/v1/union/clerk")
public class ClerkController {
    @Autowired
    private IClerkService clerkService;

    @Autowired
    private ClerkMapper clerkMapper;

    @Autowired
    private UserMapper userMapper;
    @LogAnnotation(content = "添加员工", type = LogTypeEnum.SELECT)
    @ApiOperation(value = "商家店员信息  添加接口")
    @ApiResponses({
            @ApiResponse(code = 124, message = "添加成功"),
            @ApiResponse(code = 125, message = "添加失败"),
            @ApiResponse(code = 257, message = "手机号已经被注册"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @PostMapping("")
    public ReturnResult addClerk(@RequestBody AddClerkParam addClerkParam) {
        try {
            Clerk clerk = new Clerk();
            clerk.setCreatedAt(new Date());
            clerk.setUpdatedAt(null);
            clerk.setDeletedAt(null);
            clerk.setMoblie(addClerkParam.getMobile());
            //判断手机号是否存在
            QueryWrapper<Clerk> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("moblie", addClerkParam.getMobile());
            if (clerkMapper.selectList(wrapper2).size() > 0) {
                return ReturnResultUtils.returnFailMsg(257, "手机号已经被注册！");
            }
            clerk.setName(addClerkParam.getName());
            String password = addClerkParam.getMobile().substring(addClerkParam.getMobile().length() - 6);
            clerk.setPassword(UuidUtils.sha1(password));
            clerk.setRole(0);
            clerk.setEnable(true);
            clerk.setShopId(addClerkParam.getShopId());
            clerkService.addClerk(clerk);
            QueryWrapper<Clerk> wrapper = new QueryWrapper<>();
            wrapper.eq("moblie", addClerkParam.getMobile());
            Clerk clerk1 = clerkMapper.selectOne(wrapper);
            User user = new User();
            user.setClerkId(clerk1.getId());
            user.setCreatedAt(new Date());
            userMapper.insert(user);
            return ReturnResultUtils.returnSuccess(clerk);
        } catch (Exception e) {
            log.error("添加失败" + e);
            return ReturnResultUtils.returnFailMsg(125, "添加失败");
        }
    }
    @LogAnnotation(content = "删除员工", type = LogTypeEnum.SELECT)
    @ApiOperation(value = "商家店员信息  删除接口")
    @ApiResponses({
            @ApiResponse(code = 126, message = "删除成功"),
            @ApiResponse(code = 127, message = "删除失败"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @DeleteMapping("/{id}")
    public ReturnResult deleteClerk(@PathVariable("id") Integer id) {
        try {
            clerkService.deleteClerkById(id);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("删除失败" + e);
            return ReturnResultUtils.returnFailMsg(127, "删除失败");
        }
    }

    @ApiOperation(value = "商家店员信息  修改接口")
    @ApiResponses({
            @ApiResponse(code = 128, message = "修改成功"),
            @ApiResponse(code = 129, message = "修改失败"),
            @ApiResponse(code = 257, message = "手机号已经被注册"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @LogAnnotation(content = "修改员工信息", type = LogTypeEnum.SELECT)
    @PutMapping("")
    public ReturnResult updateClerkById(@RequestBody UpdateClerkParam updateClerkParam) {
        try {
            Clerk clerk = clerkService.selectClerkById(updateClerkParam.getClerkId());
            clerk.setUpdatedAt(new Date());
            clerk.setMoblie(updateClerkParam.getMobile());
            //判断手机号是否存在
            QueryWrapper<Clerk> wrapper = new QueryWrapper<>();
            wrapper.eq("moblie", updateClerkParam.getMobile());
            if (clerkMapper.selectList(wrapper).size() > 0) {
                return ReturnResultUtils.returnFailMsg(257, "手机号已经被注册！");
            }
            clerk.setName(updateClerkParam.getName());
            String password = updateClerkParam.getMobile().substring(updateClerkParam.getMobile().length() - 6);
            clerk.setPassword(UuidUtils.sha1(password));
            clerkService.updateClerkById(clerk);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("修改失败" + e);
            return ReturnResultUtils.returnFailMsg(129, "修改失败");
        }
    }

    @ApiOperation(value = "查询商店所属所有店员", notes = "count:  为 数据的总条数")
    @ApiResponses({
            @ApiResponse(code = 130, message = "查询成功"),
            @ApiResponse(code = 131, message = "查询失败"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @GetMapping
    public ReturnResult selectClerksPage(@RequestParam(value = "shopId", required = false) Integer shopId,
                                         @RequestParam(value = "name", required = false) String name,
                                         @RequestParam(value = "mobile", required = false) String mobile,
                                         @RequestParam(value = "enable", required = false) Integer enable,
                                         @RequestParam(defaultValue = "1", required = false) Integer page,
                                         @RequestParam(defaultValue = "20", required = false) Integer limit) {
        try {
            Map map = clerkService.selectClerksPage(page, limit, shopId, name, mobile, enable);
            return ReturnResultUtils.returnSuccess(map);
        } catch (Exception e) {
            log.error("查询失败" + e);
            return ReturnResultUtils.returnFailMsg(131, "查询失败");
        }
    }

    @ApiOperation(value = "后台员工管理根据商店id查询员工")
    @GetMapping("/showClerksByShopId/{shopId}")
    public ReturnResult showClerksByShopId(@PathVariable("shopId") Long shopId, @RequestParam(defaultValue = "1", required = false) Integer page, @RequestParam(defaultValue = "20", required = false) Integer limit) {
        try {
            List<ClerkVo> clerkVos = clerkService.showClerkByShopId(shopId, page, limit);
            return ReturnResultUtils.returnSuccess(clerkVos);
        } catch (Exception e) {
            log.error("查询失败" + e);
            return ReturnResultUtils.returnFailMsg(131, "查询失败");
        }
    }
    @LogAnnotation(content = "导出员工信息", type = LogTypeEnum.SELECT)
    @ApiOperation(value = "后台员工信息导出")
    @GetMapping("/downloadClerk")
    public ReturnResult downloadClerk() {
        try {
            List<Clerk> clerks = clerkMapper.selectList(null);
            return ReturnResultUtils.returnSuccess(clerks);
        } catch (Exception e) {
            log.error("下载失败" + e);
            return ReturnResultUtils.returnFailMsg(198, "下载失败");
        }
    }
    @LogAnnotation(content = "导入员工信息", type = LogTypeEnum.ADD)
    @ApiOperation(value = "后台员工信息导入")
    @GetMapping("/importClerk")
    public ReturnResult importClerk(MultipartFile file) throws Exception {
        try {
            System.out.println("file = " + file);
            InputStream inputStream = file.getInputStream();
            ImportParams importParams = new ImportParams();
            //  声明 有一行是字段名   不读取
            importParams.setTitleRows(1);
            //  声明 有一行是标题     不读取
            importParams.setHeadRows(1);
            List<AddClerkParam> addClerkParams = ExcelImportUtil.importExcel(inputStream, AddClerkParam.class, importParams);
            //批量添加

            addClerkParams.forEach(c -> addClerk(c));
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("上传失败" + e);
            return ReturnResultUtils.returnFailMsg(197, "上传失败");
        }
    }
    @LogAnnotation(content = "修改员工密码", type = LogTypeEnum.UPDATE)
    @ApiOperation(value = "修改员工密码")
    @PutMapping("/updatePassword")
    public ReturnResult updatePassword(@RequestBody UpdateClerkPassword clerkPassword) {
        try {
            QueryWrapper<Clerk> wrapper = new QueryWrapper<>();
            wrapper.eq("id", clerkPassword.getId());
            Clerk clerk = clerkMapper.selectOne(wrapper);
            clerk.setPassword(UuidUtils.sha1(clerkPassword.getPassword()));
            clerkMapper.updateById(clerk);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("修改失败" + e);
            return ReturnResultUtils.returnFailMsg(129, "修改失败");
        }
    }

    @ApiOperation(value = "注销员工接口")
    @PutMapping(value = "/unableClerk/{id}")
    public ReturnResult unableClerk(@PathVariable(value = "id") Long id) {
        Clerk clerk = clerkMapper.selectById(id);
        clerk.setEnable(false);
        try {
            clerkMapper.updateById(clerk);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("注销员工失败！" + e);
            e.printStackTrace();
            return ReturnResultUtils.returnFailMsg(814, "注销员工失败！");
        }
    }


    @ApiOperation(value = "恢复员工接口")
    @PutMapping(value = "/enableClerk/{id}")
    public ReturnResult enableClerk(@PathVariable(value = "id") Long id) {
        Clerk clerk = clerkMapper.selectById(id);
        clerk.setEnable(true);
        try {
            clerkMapper.updateById(clerk);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("恢复员工失败！" + e);
            e.printStackTrace();
            return ReturnResultUtils.returnFailMsg(815, "恢复员工失败！");
        }
    }
}
